package com.gxa.weixing.pc.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gxa.weixing.core.exception.BusinessException;
import com.gxa.weixing.core.pojo.*;
import com.gxa.weixing.core.service.impl.BaseServiceImpl;
import com.gxa.weixing.core.util.ShiroMd5;
import com.gxa.weixing.core.util.VerifyParamUtil;
import com.gxa.weixing.pc.mapper.ManagerMapper;
import com.gxa.weixing.pc.mapper.ManagerModelMapper;
import com.gxa.weixing.pc.mapper.ManagerRoleMapper;
import com.gxa.weixing.pc.service.ManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author ChenJ
 * @date 2022/01/05 16:52
 **/
@Service("managerService")
@Transactional(rollbackFor = Throwable.class)
public class ManagerServiceImpl extends BaseServiceImpl<Manager> implements ManagerService {

    @Autowired
    private ManagerMapper managerMapper;

    @Autowired
    private ManagerModelMapper managerModelMapper;

    @Autowired
    private ManagerRoleMapper managerRoleMapper;

    @Override
    public List<Menu> getMenus(String phone) {
        // 通过get方法查询所有权限列表
        List<Menu> sourceList = managerMapper.getMenus(phone);

        // 声明一个集合，有组织的添加权限对象并分级
        List<Menu> distList = new ArrayList<>();
        for (Menu menu : sourceList) {
            // 如果pid为0，表示是一级权限，直接添加到distList集合
            if (menu.getMenuPid().equals(0L)) {
                distList.add(menu);
                // 调用递归方法
                getChildren(menu,sourceList);
            }
        }
        // 返回分级的权限集合
        return distList;
    }

    @Override
    public ManagerModel getManagerMenus(String phone) {
        ManagerModel managerModel = managerModelMapper.selectByPhone(phone);
        List<Role> roleList = managerModel.getRoleList();
        for (Role role : roleList) {
            List<Menu> menus = managerMapper.getMenus(phone);
            role.setMenuList(menus);
        }
        return managerModel;
    }

    @Override
    public Manager getByPhone(String phone) {
        return managerMapper.getByPhone(phone);
    }

    @Override
    public PageInfo getAll(Integer page, Integer size) throws ParseException {
        PageHelper.startPage(page, size);
        List<Map> all = managerMapper.getAll();
        for (Map map : all) {
            // 处理map中updateTime的时间格式
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String updateTime = df.format(df.parse(map.get("updateTime").toString()));
            map.put("updateTime",updateTime);
            // 处理map中state状态，转换为对应的描述(0/冻结 1/正常)
            String stateDesc = Integer.parseInt(map.get("state").toString()) == 0 ? "冻结" : "正常";
            map.put("state",stateDesc);
        }
        return PageInfo.of(all);
    }

    @Override
    public PageInfo getListBy(Integer page, Integer size,
            Long shopId, Long state, String name) throws ParseException {
        // 开启分页
        PageHelper.startPage(page, size);
        List<Map> listBy = managerMapper.getListBy(shopId, state, name);
        for (Map map : listBy) {
            // 处理map中updateTime的时间格式
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String updateTime = df.format(df.parse(map.get("updateTime").toString()));
            map.put("updateTime",updateTime);
            // 处理map中state状态，转换为对应的描述(0/冻结 1/正常)
            String stateDesc = Integer.parseInt(map.get("state").toString()) == 0 ? "冻结" : "正常";
            map.put("state",stateDesc);
        }
        return PageInfo.of(listBy);
    }

    @Override
    public Integer add(Map<String, String> map) throws BusinessException {
        // 所属门店的编号
        Long shopId = VerifyParamUtil.longVerifyParam(map.get("shopId"));
        // 姓名
        String name = map.get("name");
        // 手机号
        String phone = map.get("phone");
        // 权限配置组(角色)
        Long roleId = VerifyParamUtil.longVerifyParam(map.get("roleId"));
        // 账号状态
        Long state = VerifyParamUtil.longVerifyParam(map.get("state"));

        Manager manager = new Manager();
        manager.setShopId(shopId);
        manager.setManagerName(name);
        manager.setManagerState(state);
        manager.setManagerPhone(phone);
        // 默认头像
        manager.setManagerHeadPhoto("http://bucket-lijianmin.oss-cn-chengdu.aliyuncs.com/wisdomShopping/uploadImg/c12798097af847f08616a016a07686d6.jpg");
        // 修改时间
        manager.setManagerUpdateTime(new Date());
        // 默认密码
        String pwd = ShiroMd5.shiroMd5("123456");
        manager.setManagerPwd(pwd);
        // 影响行数
        Integer updates = managerMapper.insertSelective(manager);

        if (updates == 1) {
            // 添加权限组(角色)
            Example example = new Example(Manager.class);
            example.createCriteria().andEqualTo("managerPhone",phone);
            Manager manager1 = managerMapper.selectOneByExample(example);
            Long managerId = null;
            if (manager1 != null) {
                managerId = manager1.getManagerId();
            }
            ManagerRole managerRole = new ManagerRole();
            managerRole.setManagerId(managerId);
            managerRole.setRoleId(roleId);
            managerRoleMapper.insertSelective(managerRole);
        }
        return updates;
    }

    @Override
    public Integer update(Map<String, String> map) throws BusinessException {
        // 管理员的编号
        Long id = VerifyParamUtil.longVerifyParam(map.get("id"));
        // 所属门店的编号
        Long shopId = VerifyParamUtil.longVerifyParam(map.get("shopId"));
        // 姓名
        String name = map.get("name");
        // 手机号
        String phone = map.get("phone");
        // 权限配置组(角色)
        Long roleId = VerifyParamUtil.longVerifyParam(map.get("roleId"));
        // 账号状态
        Long state = VerifyParamUtil.longVerifyParam(map.get("state"));

        Manager manager = new Manager();
        // 校验参数
        if (!StringUtils.isEmpty(id)) {
            manager.setManagerId(id);
        }
        if (!StringUtils.isEmpty(shopId)) {
            manager.setShopId(shopId);
        }
        if (!StringUtils.isEmpty(name)) {
            manager.setManagerName(name);
        }
        if (!StringUtils.isEmpty(phone)) {
            manager.setManagerPhone(phone);
        }
        if (!StringUtils.isEmpty(state)) {
            manager.setManagerState(state);
        }
        // 更新
        Integer i = managerMapper.updateByPrimaryKeySelective(manager);

        // 修改所属权限
        if (!StringUtils.isEmpty(roleId) && !StringUtils.isEmpty(id)) {
            // 条件
            Example example = new Example(ManagerRole.class);
            example.createCriteria().andEqualTo("managerId",id);
            // 修改角色组
            ManagerRole managerRole = new ManagerRole();
            managerRole.setRoleId(roleId);
            managerRoleMapper.updateByExampleSelective(managerRole,example);
        }


        return i;
    }

    @Override
    public Integer delete(Long id) throws BusinessException {
        // 删除管理员信息
        int i = managerMapper.deleteByPrimaryKey(id);

        // 如果管理元删除成功,同时删除关系表中的管理员拥有的角色
        if (i == 1) {
            ManagerRole managerRole = new ManagerRole();
            managerRole.setManagerId(id);
            int delete = managerRoleMapper.delete(managerRole);
        }
        return i;
    }

    /**
     * 以当前对象的id作为pid，得到所有权限
     *
     * @param menu
     */
    void getChildren(Menu menu, List<Menu> permissionList) {

        for (Menu menu2 : permissionList) {
            if (menu2.getMenuPid().equals(menu.getMenuId())) {
                // 放
                menu.getChildren().add(menu2);

                // 如果还有子级权限，继续调用该方法(递归)
                getChildren(menu2, permissionList);
            }
        }
    }
}
